package com.demo.gateway.handler;

import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSON;
import com.demo.commons.results.CommonEnum;
import com.demo.commons.results.CommonResult;
import com.demo.commons.results.Results;

import reactor.core.publisher.Mono;

/**
 * 自定义返回结果：没有登录或token过期时 Created by macro on 2020/6/18.
 */
@Component
public class RestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
	@Override
	public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
		ServerHttpResponse response = exchange.getResponse();
		String token = getToken(exchange);
		if (StringUtils.isBlank(token)) {
			CommonResult<?> result = Results.build(CommonEnum.AUTH_VER);
			DataBuffer buffer = response.bufferFactory()
					.wrap(JSON.toJSONString(result).getBytes(Charset.forName("UTF-8")));
			return response.writeWith(Mono.just(buffer));
		}
		response.setStatusCode(HttpStatus.OK);
		response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
		// String body= JSONUtil.toJsonStr(CommonResult.unauthorized(e.getMessage()));
		// String body = "test";
		CommonResult<?> result = Results.build(CommonEnum.ACCESS_TOKEN_ERROR);
		DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes(Charset.forName("UTF-8")));
		return response.writeWith(Mono.just(buffer));
	}

	private String getToken(ServerWebExchange exchange) {
		String token = exchange.getRequest().getHeaders().getFirst("Authorization");
		if(StringUtils.isNotBlank(token)) {
			token = token.replace("Bearer ", "");
		}
		return token;
	}
}
